<template>
    <a-alert class="error mb16" v-if="errors.length" type="error" showIcon :message="`保存成员时发生错误：`">
        <template #description>
            <ul>
                <li v-for="(v, k) in errors" :key="k">{{ v }}</li>
            </ul>
        </template>
    </a-alert>
    <a-alert class="mb16" v-else type="info" showIcon message="填写提示">
        <template #description>
            <ol>
                <li>指导老师的<strong>第一条</strong>是<strong>审核项目的老师</strong>，项目组成员的<strong>第一条</strong>是<strong>项目的负责人</strong>；</li>
                <li>点击“添加”按钮可以添加一位新成员或者一位新指导老师；</li>
                <li>输完学/工号之后，只需要按下回车或者离开文本框，即可自动加载姓名，专业班级，所在学院等字段；</li>
                <li>在此页面仅需要填写 学/工号，分工 字段；</li>
                <li>使用 上移，下移 即可移动成员顺序；</li>
                <li>在保存时，系统会自动删除所有空行。</li>
            </ol>
        </template>
    </a-alert>
    <teacher-editor class="mb16" :max-capacity="10" ref="teacherRef" />
    <student-editor class="mb16" :max-capacity="5" ref="studentRef" />
    <a-flex justify="space-between">
        <a-space>
            <a-button type="primary" @click="save" :loading><SaveOutlined />保存成员数据</a-button>
            <a-button @click="reset" :loading ><ReloadOutlined />还原所有修改</a-button>
        </a-space>
        <a-button type="primary" :loading>
            保存并前往下一页
            <ArrowRightOutlined />
        </a-button>
    </a-flex>
    
</template>

<script setup>
import TeacherEditor from '@proj/components/teacher-editor.vue'
import StudentEditor from '@proj/components/student-editor.vue'
import { ref, inject } from 'vue'
import { axios } from '@/axios';
import app from '@/app';
import cache from '@proj/ProjectCache';

const teacherRef = ref();
const studentRef = ref();
const errors = ref([]);
const data = inject("data");
const loading = ref(false);
function reset () {
    const tea = teacherRef.value;
    const stu = studentRef.value;

    tea.reset();
    stu.reset();
}

// 创新训练人数限制：指导老师至少1人，参与人（含组长）不超过5人
async function save () {
    const tea = teacherRef.value;
    const stu = studentRef.value;
    
    let flag = await tea.validate();
    flag &= await stu.validate();
    errors.value = [...tea.errorStrings, ...stu.errorStrings];
    if (!flag) return;

    let handler = app.modals.loading("正在提交数据");
    loading.value = true;
    let msg = await axios.post("/api/proj/common/SaveMembers", {
        id: data.basicInfo.ID,
        teachers: tea.members,
        students: stu.members
    });

    app.modals.showResponse(msg);
    if (msg.success) {
        data.setMembers(msg.basicInfo, msg.otherTeachers, msg.members);
    } else {
        errors.value = [msg.msg];
    }   
    
    loading.value = false;
    handler();
}
async function validate(){
    return await teacherRef.value.validate() && await studentRef.value.validate();
}
defineExpose({
    validate
});
</script>

<style lang="less" scoped>
ol {
    list-style: decimal;
}
</style>